<template>
  <div class="warpper-box">
    <div class="inner_box">
      <el-form :inline="true" size="small" :model="formInline" ref="formInline">
        <el-form-item label="考核周期" prop="time">
          <el-date-picker
            v-model="formInline.time"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应商类别" prop="categoryName">
          <el-cascader
            placeholder="支持搜索，多选"
            filterable
            v-model="formInline.categoryName"
            :props="{ multiple: true, checkStrictly: true }"
            :options="treeData"
            clearable
            @change="findChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="formInline.name" placeholder="公司名称"></el-input>
        </el-form-item>
        <el-form-item label="评价结论" prop="evaluationConclusion">
          <el-input
            v-model="formInline.evaluationConclusion"
            placeholder="模糊搜索"
          ></el-input>
        </el-form-item>
        <el-form-item label="考核类型" prop="supplierCategory">
          <el-select v-model="formInline.supplierCategory" placeholder="请选择">
            <el-option label="全部" value=""> </el-option>
            <el-option label="工程和货物类" value="1"> </el-option>
            <el-option label="服务类" value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="loadList(true)"
            >搜索</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-setting"
            @click="reset('formInline')"
            >重置</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-upload"
            size="small"
            :disabled="tableData.length == 0"
            @click="dataXlsx(true)"
            >导出EXCEL</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        :data="tableData"
        ref="tableRef"
        style="width: 100%"
        :header-cell-style="headerCellStyle"
        :cell-style="cellStyle"
        border
        stripe
      >
        <el-table-column label="序号" width="50" align="center" :index="1">
          <template #default="scope">
            {{ (models.pageNum - 1) * models.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="考核周期" width="120">
          <template #default="scope">
            {{ scope.row.evaluationStartDate | intervalTime }} 至
            {{ scope.row.evaluationEndDate | intervalTime }}
          </template>
        </el-table-column>
        <el-table-column
          label="供应商类别"
          resizable
          show-overflow-tooltip
          width="120"
          prop="categoryName"
        />
        <el-table-column
          label="公司名称"
          resizable
          show-overflow-tooltip
          width="120"
          prop="supplierName"
        >
          <template #default="scope">
            <label class="link-box" @click="supplierDetail(scope.row)">{{
              scope.row.supplierName
            }}</label>
          </template>
        </el-table-column>
        <el-table-column
          label="履约过程、廉洁、综合评价扣分情况"
          show-overflow-tooltip
          resizable
          :class-name="ageColumnClass"
        >
          <template #default="scope">
            <ul class="uls">
              <li
                v-for="(items, colIndex) in scope.row.projectCountInfo"
                :key="colIndex"
                class="lis"
              >
                <label>{{ items.name }}</label>
                <span>{{ items.score }}</span>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column
          label="投标过程扣分情况"
          show-overflow-tooltip
          resizable
          width="80"
          prop="bidProcessDeduction"
        />
        <el-table-column
          label="最终扣分"
          show-overflow-tooltip
          resizable
          width="80"
          prop="totalDeduction"
        />
        <el-table-column
          label="投标过程考核评价结论分情况"
          resizable
          show-overflow-tooltip
          width="140"
          prop="evaluationConclusion"
        />
        <el-table-column
          label="备注"
          resizable
          show-overflow-tooltip
          width="140"
          prop="remark"
        />
        <el-table-column label="操作" fixed="right" width="100" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="setRemark(scope.row)"
              >设置备注</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <el-pagination
          class="page-footer"
          background
          layout="total,prev,pager,next,sizes,jumper"
          :total="total"
          :page-sizes="[10, 20, 30, 40, 50]"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </el-row>
    </div>
    <supplierDetail ref="createSupplierDetail" />
  </div>
</template>

<script>
import moment from "moment";
import XLSX from "xlsx";
import { mapGetters, mapActions } from "vuex";
import {
  getEvaluationPage,
  getEvaluationExport,
  getSupplierCategoryTree,
  getEvaluationSave
} from "@/api/supplier_api";
import { checkEmail, checkPhone, TreeArrar } from "@/utils/index";
import supplierDetail from "./supplier_detail.vue";
import { xlsx } from "@/utils/xlsx";
export default {
  components: {
    supplierDetail
  },
  data() {
    return {
      formInline: {
        name: "",
        categoryName: [],
        cateoryId: "",
        evaluationConclusion: "",
        supplierCategory: "",
        time: []
      },
      treeData: [],
      total: 1,
      tableData: [],
      models: {
        pageNum: 1,
        pageSize: 10
      }
    };
  },
  filters: {
    intervalTime(val) {
      if (!val) {
        return;
      }
      return moment(val).format("YYYY-MM-DD");
    }
  },
  computed: {
    ...mapGetters(["findType"]),
    ageColumnClass() {
      return "custom-age-column";
    }
  },
  mounted() {
    this.loadList(true);
    this.categoryList();
  },
  methods: {
    async categoryList() {
      const { code, data } = await getSupplierCategoryTree();
      if (code == 200) {
        if (data && data.length) {
          let NewData = data.map(ele => TreeArrar(ele));
          this.treeData = NewData;
        }
      }
    },
    async loadList(formData) {
      let param = {};
      if (typeof formData === "boolean") {
        this.models.pageNum = 1;
        this.models.pageSize = 10;
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected();
        }
      }
      if (typeof formData === "object") {
        this.models.pageNum = formData.pageNum;
        this.models.pageSize = formData.pageSize;
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected();
        }
      }
      if (this.formInline.categoryName && this.formInline.categoryName.length) {
        param.categoryName = this.formInline.categoryName;
      }

      if (this.formInline.time && this.formInline.time.length) {
        param.evaluationTimeStart = this.formInline.time[0];
        param.evaluationTimeEnd = this.formInline.time[1];
      }
      param.evaluationConclusion = this.formInline.evaluationConclusion;
      param.supplierCategory = this.formInline.supplierCategory;
      param.name = this.formInline.name;
      param.pageNum = this.models.pageNum;
      param.pageSize = this.models.pageSize;
      const { code, data } = await getEvaluationPage(param);
      if (code == 200) {
        const regex = /#~#/;
        data.list.forEach(v => {
          if (regex.test(v.projectCountInfo)) {
            const parts = v.projectCountInfo.split("#~#");
            v.projectCountInfo = JSON.parse(parts[0]);
          } else {
            v.projectCountInfo = JSON.parse(v.projectCountInfo);
          }

          // if (v.projectCountInfo) {
          //   const filteredStr = v.projectCountInfo.replace(/\r\n/g, '');
          //   v.projectCountInfo = JSON.parse(filteredStr)
          // }
        });
        this.tableData = data.list;
        this.total = data.total;
      }
    },
    handlePageChange(page) {
      this.models.pageNum = page;
      this.loadList();
    },
    handleSizeChange(page) {
      this.models.pageSize = page;
      this.loadList();
    },
    headerCellStyle({ column }) {
      return {
        padding: "6px 0"
      };
    },
    cellStyle({ column }) {
      // 改变指定列（如第二列）的表格内容样式
      if (column.label === "履约过程、廉洁、综合评价扣分情况") {
        return {
          padding: "0"
        };
      }
      return {};
    },
    findChange(values) {
      // console.log(values)
      // let parentNodes = [];
      // values.forEach(childId => {
      //   const parent = this.findParentNode(this.treeData, childId);
      //   if (parent) {
      //     parentNodes.push({ childId, parent });
      //   }
      // });
    },
    findParentNode(nodes, childId, parent = null) {
      for (const node of nodes) {
        if (node.value === childId) {
          return parent; // 返回父节点
        }
        if (node.children && node.children.length > 0) {
          const found = this.findParentNode(node.children, childId, node);
          if (found) {
            return found; // 返回找到的父节点
          }
        }
      }
      return null; // 未找到
    },
    getLabelsByValues(options, values) {
      const labels = [];
      let currentOptions = options;
      // 遍历 values，逐级查找对应的 label
      values.forEach(value => {
        const found = currentOptions.find(option => option.value === value);
        if (found) {
          labels.push(found.label);
          currentOptions = found.children || [];
        }
      });

      return labels;
    },
    onOk(result) {
      this.tableKey++;
      this.loadList(result);
    },
    reset(formName) {
      this.$refs[formName].resetFields();
      this.formInline.cateoryId = "";
      this.loadList(true);
    },
    supplierDetail(row) {
      this.$refs.createSupplierDetail.openDetail(row);
    },
    setRemark(row) {
      let that = this;
      this.$prompt("请输入备注", "备注信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^\S+$/,
        inputErrorMessage: "备注信息不能为空",
        inputValue: row.remark,
        closeOnClickModal: false
      })
        .then(({ value }) => {
          let param = {};
          param.remark = value;
          param.id = row.id;
          param.supplierId = row.supplierId;
          param.supplierStoreId = row.supplierStoreId;
          getEvaluationSave(param).then(res => {
            that.loadList(true);
          });
        })
        .catch(err => {});
    },
    async dataXlsx() {
      /* let param = {};
      if (this.formInline.applyCategoryId&&this.formInline.applyCategoryId.length) {
        param.applyCategoryId = this.formInline.applyCategoryId.join(',')
      }

      if (this.formInline.time && this.formInline.time.length) {
        param.storeStartTime = this.formInline.time[0]
        param.storeEndTime = this.formInline.time[1]
      }

      param.name = this.formInline.name;
      param.pageNum = 1;
      param.pageSize = this.total;
      const response = await getEvaluationExport(param)
      const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = '台帐列表.xlsx';
      link.click();
      URL.revokeObjectURL(url);
      */

       let param = {};
      
      if (this.formInline.categoryName && this.formInline.categoryName.length) {
        param.categoryName = this.formInline.categoryName;
      }

      if (this.formInline.time && this.formInline.time.length) {
        param.evaluationTimeStart = this.formInline.time[0];
        param.evaluationTimeEnd = this.formInline.time[1];
      }
      param.evaluationConclusion = this.formInline.evaluationConclusion;
      param.supplierCategory = this.formInline.supplierCategory;
      param.name = this.formInline.name;
      param.pageNum = 1;
      param.pageSize = this.total;
      const { code, data } = await getEvaluationPage(param);
      const result = data?.list ?? []
      const regex = /#~#/;
      result.forEach(v => {
        if (regex.test(v.projectCountInfo)) {
          const parts = v.projectCountInfo.split("#~#");
          v.projectCountInfo = JSON.parse(parts[0]);
        } else {
          v.projectCountInfo = JSON.parse(v.projectCountInfo);
        }
      });
      let fields = {
        title0: "序号",
        title1: "考核周期",
        title2: "供应商类别",
        title3: "公司名称",
        title4: "履约过程、廉洁、综合评价扣分情况",
        title5: "投标过程扣分情况",
        title6: "最终扣分",
        title7: "投标过程考核评价结论分情况",
        title8: "备注"
      };
      let arry = [];
      let i = 0;
      result.forEach(ele => {
        i++;
        const time = moment(ele.evaluationStartDate).format("YYYY-MM-DD") + ' 至 ' + moment(ele.evaluationEndDate).format("YYYY-MM-DD");
        let projectCountInfo = "";
        for (let key in ele.projectCountInfo) {
          projectCountInfo += ele.projectCountInfo[key].name + "（" + ele.projectCountInfo[key].score + "分）" + " ｜ ";
        }
        arry.push({
          title0: i,
          title1: time,
          title2: ele.categoryName,
          title3: ele.supplierName,
          title4: projectCountInfo.replace(/ ｜ $/, ''),
          title5: ele.bidProcessDeduction,
          title6: ele.totalDeduction,
          title7: ele.evaluationConclusion,
          title8: ele.remark
        });
      });

      const manualWidthColumns = [
        { width: 10 },
        { width: 30 },
        { width: 25 },
        { width: 40 },
        { width: 100 },
        { width: 20 },
        { width: 15 },
        { width: 100 },
        { width: 100 }
      ];

      xlsx(arry, fields, manualWidthColumns, "评审台帐列表");
      /*
      const headers = ['考核周期', '爱好', '年龄'];
      const tableData = [
        ['张三', [{id:59,score:1,name:"外滩项目"}], 25],
        ['李四', ['绘画', '音乐'], 22],
        ['王五', ['篮球', '游泳'], 28]
      ]
      const wsData = [headers];
      tableData.forEach(row => {
        const newRow = [];
        row.forEach((cell, index) => {
          if (index === 1) {
            newRow.push(cell.join(' | '));
          } else {
            newRow.push(cell);
          }
        });
        wsData.push(newRow);
      });
      const ws = XLSX.utils.aoa_to_sheet(wsData);

        ws['!cols'] = [
        { wch: 10 }, // 姓名列宽设置为10个字符宽
        { wch: 50 },  // 年龄列宽设置为5个字符宽
        { wch: 10 }   // 职业列宽设置为10个字符宽
      ];

      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
      XLSX.writeFile(wb, 'exported_data.xlsx');

      */
    }
  }
};
</script>
<style scoped>
.uls {
  margin: 0;
  padding: 0;
  list-style: none;
  display: flex;
}
.uls li {
  flex: 1;
  text-align: center;
  border-right: 1px solid #ebeef5;
  display: grid;
  grid-template-rows: 1fr 0.5fr;
  align-items: center;
}
.uls li:last-child {
  border-right: 0;
}
.uls li label {
  padding: 0 6px;
  word-wrap: break-word;
  white-space: pre-wrap;
  width: 100%;
}
.uls li span {
  padding-top: 6px;
  width: 100%;
  border-top: 1px solid #ebeef5;
}
</style>
